__author__ = 'zhengxiaoyu'
from Tkinter import *
import tkMessageBox
import tkFileDialog
import csv
class GradingInterface(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grade = []
        self.pack()
        self.createWidgets()
        self.grading()

    def createWidgets(self):
        self.inputButton = Button(self, text='Input', command=self.input)
        self.inputButton.pack(side=TOP,    expand=YES, fill=BOTH)
        self.outputButton = Button(self, text='Output', command=self.output)
        self.outputButton.pack(side=TOP,    expand=YES, fill=BOTH)

    def grading(self):
        self.addFrame = Toplevel()
        self.addFrame.geometry("400x300")
        self.addFrame.title("GRADING")
        self.userLabel = Label(self.addFrame, text="ID")
        self.gradeLabel = Label(self.addFrame, text="grade")
        self.newUserID = Entry(self.addFrame)
        self.newUserGrade = Entry(self.addFrame)
        self.userLabel.pack()
        self.newUserID.pack()
        self.gradeLabel.pack()
        self.newUserGrade.pack()
        Button(self.addFrame, text="OK", command=self.gradeok).pack()

    def gradeok(self):
        if self.newUserID.get() and self.newUserGrade.get() :
            #self.allowIPFrame = Toplevel()
            for i in self.grade:
                if i[0] == self.newUserID.get():
                    tkMessageBox.showinfo("Rewrite the Score", "You will rewrite the score")
                    self.grade.remove(i)
            self.grade.append((self.newUserID.get(), self.newUserGrade.get()))
            tkMessageBox.showinfo("Input Success", "Please input the next score")
            self.addFrame.destroy()
            self.grading()

        else:
            tkMessageBox.showinfo("Wrong Input", "Please reinput the score")
            self.addFrame.destroy()
            self.grading()



    def input(self):
        file = tkFileDialog.askopenfile()
        reader = csv.reader(file)
        flag = 0

        for i in reader:
            if i[0] == 'ID' and i[1] == 'GRADE':
                flag = 1
                break
        if flag:
            for i in reader:
                if i[0] != 'ID':
                    self.grade.append((i[0], i[1]))
            tkMessageBox.showinfo("File Input Success", "File OK")

        else:
            tkMessageBox.showinfo("Wrong File", "Input another file")
        file.close()
        return

    def output(self):
        file = tkFileDialog.asksaveasfile()
        #csvfile = file('grade.csv', 'wb')
        writer = csv.writer(file)
        writer.writerow(['ID','GRADE'])
        writer.writerows(self.grade)
        file.close()
        tkMessageBox.showinfo("File Write Complete", "File generated")
        return


app = GradingInterface()
app.master.title('Grading Machine')
app.mainloop()